local RoomBase = require 'packages.wenhe_yanbing.wenhe_yanbing.core.roombase'
local GameLogic = require "packages.wenhe_yanbing.wenhe_yanbing.server.gamelogic"
local ServerPlayer = require "packages.wenhe_yanbing.wenhe_yanbing.server.serverplayer"

---@class WenheYanbing.Room : WenheYanbing.RoomBase, ServerRoomBase
local Room = RoomBase:subclass("WenheYanbing.Room")
Room:include(Fk.Base.ServerRoomBase)

function Room:initialize(_room)
    RoomBase.initialize(self)
    Fk.Base.ServerRoomBase.initialize(self, _room)

    self.serverplayer_klass = ServerPlayer
    self.logic_klass = GameLogic
    
    -- 设置玩家房间引用
    self:setupPlayerRoomReferences()
end

-- 设置玩家房间引用
function Room:setupPlayerRoomReferences()
    for _, player in ipairs(self.players) do
        player:setRoom(self)
    end
end

-- 重写添加玩家方法，确保设置房间引用
function Room:addPlayer(player)
    Fk.Base.ServerRoomBase.addPlayer(self, player)
    player:setRoom(self)
end

-- 发送招募阶段通知
function Room:notifyRecruitPhase()
    -- 只发送可序列化的数据
    local playerData = {}
    for _, player in ipairs(self.players) do
        table.insert(playerData, {
            id = player.id,
            name = player.name,
            kingdom = player.kingdom,
            health = player.health,
            gold = player.gold,
            tavernTier = player.tavernTier
        })
    end
    
    self:doBroadcastNotify("RecruitPhase", {
        turn = self.turn,
        phase = "recruit",
        players = playerData  -- 只发送基本数据，不发送整个玩家对象
    })
end

-- 发送战斗阶段通知
function Room:notifyCombatPhase()
    self:doBroadcastNotify("CombatPhase", {
        turn = self.turn,
        phase = "combat"
    })
end

-- 向特定玩家发送通知
function Room:notifyPlayer(player, command, data)
    if player and player.doNotify then
        player:doNotify(command, data)
    end
end

-- 处理玩家操作
function Room:handlePlayerAction(player, data)
    local action = data.action
    local actionData = data.data or {}
    
    local success = false
    local result = {}
    
    if action == "buy" then
        success = player:buyMinion(actionData.tavernIndex)
        if success then
            result.tavernMinions = self:serializeMinions(player.tavernMinions)
            result.gold = player.gold
            result.hand = self:serializeMinions(player.hand)
        end
    elseif action == "refresh" then
        success = player:refreshTavern()
        if success then
            result.tavernMinions = self:serializeMinions(player.tavernMinions)
            result.gold = player.gold
        end
    elseif action == "levelup" then
        success = player:upgradeTavern()
        if success then
            result.tavernTier = player.tavernTier
            result.gold = player.gold
            result.upgradeCost = player:getUpgradeCost()
        end
    elseif action == "freeze" then
        success = player:freezeTavern()
        if success then
            result.freezeTavern = player.freezeTavern
        end
    elseif action == "place" then
        success = player:placeMinion(actionData.handIndex, actionData.boardPosition)
        if success then
            result.hand = self:serializeMinions(player.hand)
            result.board = self:serializeMinions(player.board)
        end
    elseif action == "sell" then
        success = player:sellMinion(actionData.boardPosition)
        if success then
            result.board = self:serializeMinions(player.board)
            result.gold = player.gold
        end
    end
    
    -- 发送更新给玩家
    if success then
        self:notifyPlayer(player, "PlayerAction", {
            success = true,
            action = action,
            result = result
        })
        
        -- 同时发送进入招募状态，让客户端更新UI
        self:notifyPlayer(player, "EnterRecruit", {
            tavernMinions = self:serializeMinions(player.tavernMinions),
            gold = player.gold,
            hand = self:serializeMinions(player.hand),
            board = self:serializeMinions(player.board),
            tavernTier = player.tavernTier,
            upgradeCost = player:getUpgradeCost(),
            freezeTavern = player.freezeTavern
        })
    else
        self:notifyPlayer(player, "PlayerAction", {
            success = false,
            action = action,
            error = "操作失败"
        })
    end
    
    return success
end

-- 序列化随从数据，移除函数等不可序列化的内容
function Room:serializeMinions(minions)
    local result = {}
    for _, minion in ipairs(minions) do
        table.insert(result, {
            id = minion.id,
            name = minion.name,
            tier = minion.tier,
            attack = minion.attack,
            health = minion.health,
            kingdom = minion.kingdom,
            skills = minion.skills,  -- 假设skills是表或数字
            cost = minion.cost,
            isGolden = minion.isGolden or false,
            hasTaunt = minion.hasTaunt or false
        })
    end
    return result
end

return Room